<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <mall@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\mall\controller\admin;

use app\mall\base\MallAdminBase;

use app\mall\model\MallGoods as MallGoodsModel;
use app\mall\model\MallGoodsData as MallGoodsDataModel;
use app\mall\model\MallCategory as MallCategoryModel;

class Goods extends MallAdminBase{
    //当前控制器菜单
    public $submenu = [];

    /**
     * TP初始化方法
     */
    public function _initialize() {
        parent::_initialize();
        $this->submenu[] = ['title' => '商品列表', 'url' => url('mall/admin.goods/index'), 'icon' => '&#xe60a;'];
        $this->submenu[] = ['title' => '添加商品', 'url' => url('mall/admin.goods/add'), 'icon' => '&#xe608;'];
    }

    /**
     * 后台商品列表
     * @access public
     * @return \think\Response
     */
    public function index(){
        $list = MallGoodsModel::order('update_time desc,id desc')->paginate(config('mn_admin.admin_pagesize'));
        // 实例化栏目模型
        $MallCategory = new MallCategoryModel;
        $this->assign([
            'submenu' => $this->submenu,
            'list' => $list,
            'categorys' => $MallCategory->getTreeOption()
        ]);
    	return $this->fetch();
    }

    /**
     * 后台商品增加
     * @access public
     * @return \think\Response
     */
    public function add(){
        // 实例化栏目模型
        $MallCategoryModel = new MallCategoryModel;
        // 实例化商品模型
        $MallGoodsModel = new MallGoodsModel;
        // POST提交数据
        if($this->request->isPost()){
            $post_data = $this->buildParam();
            // 验证主表字段
            $validate_result = $this->validate($post_data,'MallGoods');
            if(true !== $validate_result){
                $this->error($validate_result);
            }
            // 验证附表字段
            $validate_result = $this->validate($post_data,'MallGoodsData.add');
            if(true !== $validate_result){
                $this->error($validate_result);
            }
            // 设置规格默认值
            $post_data['goods_spec'] = isset($post_data['goods_spec']) && $post_data['goods_spec'] ? $post_data['goods_spec'] : [];
            // 规格加价验证
            if(!$MallGoodsModel->specMarkupValidate($post_data['goods_spec'])){
                $this->error('规格价格错误');
            }
            // 关联附表新增
            if ($MallGoodsModel->allowField(true)->save($post_data)) {
                // 实例化商品附表模型
                $MallGoodsDataModel = new MallGoodsDataModel;
                $MallGoodsDataModel->goods_desc = $post_data['goods_desc'];
                $MallGoodsDataModel->goods_spec = $post_data['goods_spec'];
                $MallGoodsModel->goodsData()->save($MallGoodsDataModel);
                $this->success('产品添加成功','index');
            }else{
                $error_msg = $MallGoodsModel->getError() ? $MallGoodsModel->getError() : $MallGoodsDataModel ? $MallGoodsDataModel : '产品添加失败，请重试';
                $this->error($error_msg);
            }
        }
        $this->assign([
            'submenu' => $this->submenu,
            'categorys' => $MallCategoryModel->getTreeOption(),
            'mall_goods_specs' => cache('mall_goods_specs')
        ]);
        return $this->fetch();
    }

    /**
     * 后台商品修改
     * @access public
     * @return \think\Response
     */
    public function edit($id = 0){
        $id = (int)$id;
        if(!$id){
            $this->error('缺少参数id','index');
        }
        // 实例化栏目模型
        $MallCategoryModel = new MallCategoryModel;
        // 查询商品信息
        $goods = MallGoodsModel::get($id, 'goodsData');
        if(!$goods){
            $this->error('产品不存在','index');
        }
        // POST提交数据
        if($this->request->isPost()){
            $post_data = $this->buildParam();
            // 验证主表字段
            $validate_result = $this->validate($post_data,'MallGoods');
            if(true !== $validate_result){
                $this->error($validate_result);
            }
            // 验证附表字段
            $validate_result = $this->validate($post_data,'MallGoodsData');
            if(true !== $validate_result){
                $this->error($validate_result);
            }
            // 设置规格默认值
            $post_data['goods_spec'] = isset($post_data['goods_spec']) && $post_data['goods_spec'] ? $post_data['goods_spec'] : [];
            // 规格加价验证
            if(!$goods->specMarkupValidate($post_data['goods_spec'])){
                $this->error('规格价格错误');
            }
            if (false !== $goods->allowField(true)->save($post_data)) {
                $goods->goods_data->goods_desc = $post_data['goods_desc'];
                $goods->goods_data->goods_spec = $post_data['goods_spec'];
                $goods->goods_data->save();
                $this->success('产品修改成功','index');
            }else{
                $this->error($goods->getError());
            }
        }
        $this->assign([
            'submenu'   => $this->submenu,
            'data'      => $goods,
            'categorys' => $MallCategoryModel->getTreeOption((int)$goods->getData('catid')),
            'mall_goods_specs' => cache('mall_goods_specs')
        ]);
        return $this->fetch();
    }

    /**
     * 后台产品删除
     * @access public
     * @return void
     */
    public function del($id = 0){
        $id = (int)$id;
        if(!$id){
            $this->error('缺少产品id');
        }
        $goods = MallGoodsModel::get($id);
        if(!$goods){
            $this->error('需要删除的产品不存在');
        }
        // 删除产品缩略图
        if(!empty($goods->goods_thumb)){
            $thumb_path = '.'.str_replace('\\', '/', $goods->goods_thumb);
            if(is_file($thumb_path)){
                if(!unlink($thumb_path)){
                    $this->error('产品缩略图删除失败，请检查权限！', 'index');
                }
            }
        }
        // 删除产品图片
        if(!empty($goods->goods_img)){
            foreach ($goods->goods_img as $key => $value) {
                if(!empty($value)){
                    $goods_img_path = '.'.str_replace('\\', '/', $value);
                    if(is_file($goods_img_path)){
                        if(!unlink($goods_img_path)){
                            $this->error('产品图片删除失败，请检查权限！', 'index');
                        }
                    }
                }
            }
        }
        // 同步删除产品附表内容
        $goods->together('goodsData')->delete();
        $this->success('产品删除成功', 'index');
    }
}